'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  // 获取当前用户ID（从客户端调用时会自动获取）
  const userId = context.CLIENTUA ? context.CLIENTUA : null;
  
  // 如果没有用户ID，尝试从token获取
  let actualUserId = userId;
  if (!actualUserId && event.uniIdToken) {
    try {
      // 使用 uniCloud 内置的用户验证
      const uniIdCommon = uniCloud.importObject('uni-id-co');
      const checkTokenRes = await uniIdCommon.checkToken({
        token: event.uniIdToken
      });
      if (checkTokenRes && checkTokenRes.uid) {
        actualUserId = checkTokenRes.uid;
      }
    } catch (error) {
      console.error('[getCustomerServiceMessages] token验证失败:', error);
    }
  }
  
  // 如果还是没有用户ID，从上下文中获取
  if (!actualUserId && context.CLIENTUA) {
    actualUserId = context.CLIENTUA;
  }
  
  // 最后的fallback：从event中获取
  if (!actualUserId && event.userId) {
    actualUserId = event.userId;
  }
  
  try {
    if (!actualUserId) {
      // 如果实在获取不到用户ID，返回空数据而不是报错
      console.warn('[getCustomerServiceMessages] 无法获取用户ID，返回空数据');
      return {
        code: 200,
        msg: '获取成功',
        data: []
      };
    }

    console.log('[getCustomerServiceMessages] 当前用户ID:', actualUserId);
    
    // 从客服消息表查询消息
    const result = await db.collection('customer-service-messages')
      .where(db.command.or([
        {
          senderId: actualUserId,
          receiverId: 'customer_service'
        },
        {
          senderId: 'customer_service',
          receiverId: actualUserId
        }
      ]))
      .orderBy('createTime', 'asc')
      .limit(100)
      .get();

    console.log('[getCustomerServiceMessages] 查询到消息数量:', result.data.length);

    // 处理消息数据，转换为前端需要的格式
    const messages = result.data.map(msg => ({
      _id: msg._id,
      type: msg.messageType || 'text',
      senderId: msg.senderId,
      senderNickname: msg.senderNickname,
      senderAvatar: msg.senderAvatar,
      receiverId: msg.receiverId,
      content: msg.content,
      imageUrl: msg.imageUrl,
      createTime: msg.createTime,
      status: msg.status || 'sent'
    }));

    // 标记所有未读消息为已读
    try {
      await db.collection('customer-service-messages')
        .where({
          senderId: 'customer_service',
          receiverId: actualUserId,
          status: db.command.neq('read')
        })
        .update({
          status: 'read',
          readTime: new Date()
        });
    } catch (updateError) {
      console.error('[getCustomerServiceMessages] 标记已读失败:', updateError);
    }

    return {
      code: 200,
      msg: '获取成功',
      data: messages
    };

  } catch (error) {
    console.error('[getCustomerServiceMessages] 查询失败:', error);
    return {
      code: 500,
      msg: '服务器错误',
      error: error.message
    };
  }
};

